package com.example.smartpark.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.smartpark.common.Result;
import com.example.smartpark.dto.PaymentDTO;
import com.example.smartpark.dto.PaymentQueryDTO;
import com.example.smartpark.model.Payment;
import com.example.smartpark.service.PaymentService;
import com.example.smartpark.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/payments")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    /**
     * 分页查询支付记录
     *
     * @param queryDTO 查询条件
     * @param token JWT令牌
     * @return 支付记录分页结果
     */
    @GetMapping
    public Result<IPage<PaymentDTO>> getPaymentPage(
            PaymentQueryDTO queryDTO,
            @RequestHeader("Authorization") String token) {
        log.info("分页查询支付记录: queryDTO={}", queryDTO);
        
        // 从token中获取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        
        // 设置用户ID（普通用户只能查询自己的支付记录）
        queryDTO.setUserId(userId);
        
        return Result.success(paymentService.getPaymentPage(queryDTO));
    }

    /**
     * 查询支付记录详情
     *
     * @param id 支付记录ID
     * @return 支付记录详情
     */
    @GetMapping("/{id}")
    public Result<PaymentDTO> getPaymentById(@PathVariable Long id) {
        log.info("查询支付记录详情: id={}", id);
        return Result.success(paymentService.getPaymentById(id));
    }

    /**
     * 创建支付订单
     *
     * @param paymentDTO 支付DTO
     * @param token JWT令牌
     * @return 创建的支付订单
     */
    @PostMapping
    public Result<PaymentDTO> createPayment(
            @RequestBody @Valid PaymentDTO paymentDTO,
            @RequestHeader("Authorization") String token) {
        log.info("创建支付订单: paymentDTO={}", paymentDTO);
        
        // 从token中获取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        
        // 设置用户ID
        paymentDTO.setUserId(userId);
        
        return Result.success(paymentService.createPayment(paymentDTO));
    }

    /**
     * 完成支付
     *
     * @param id 支付记录ID
     * @param paymentData 支付方式数据
     * @param transactionId 交易流水号
     * @return 更新后的支付记录
     */
    @PutMapping("/{id}/complete")
    public Result<PaymentDTO> completePayment(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> paymentData,
            @RequestParam String transactionId) {
        log.info("完成支付: id={}, paymentData={}, transactionId={}", id, paymentData, transactionId);
        
        Integer paymentMethod = paymentData.get("paymentMethod");
        if (paymentMethod == null) {
            return Result.error(400, "支付方式不能为空");
        }
        
        // 先更新支付方式
        PaymentDTO payment = paymentService.getPaymentById(id);
        if (payment == null) {
            return Result.error(404, "支付记录不存在");
        }
        
        // 设置支付方式并更新
        payment.setPaymentMethod(paymentMethod);
        paymentService.updatePaymentMethod(id, paymentMethod);
        
        return Result.success(paymentService.completePayment(id, transactionId));
    }

    /**
     * 取消支付
     *
     * @param id 支付记录ID
     * @param remark 取消原因
     * @return 取消后的支付记录
     */
    @PutMapping("/{id}/cancel")
    public Result<PaymentDTO> cancelPayment(
            @PathVariable Long id,
            @RequestParam(required = false) String remark) {
        log.info("取消支付: id={}, remark={}", id, remark);
        return Result.success(paymentService.cancelPayment(id, remark));
    }

    /**
     * 退款
     *
     * @param id 支付记录ID
     * @param remark 退款原因
     * @return 退款后的支付记录
     */
    @PutMapping("/{id}/refund")
    public Result<PaymentDTO> refundPayment(
            @PathVariable Long id,
            @RequestParam(required = false) String remark) {
        log.info("退款: id={}, remark={}", id, remark);
        return Result.success(paymentService.refundPayment(id, remark));
    }

    /**
     * 根据订单号查询支付记录
     *
     * @param orderNumber 订单号
     * @return 支付记录
     */
    @GetMapping("/order/{orderNumber}")
    public Result<PaymentDTO> getPaymentByOrderNumber(@PathVariable String orderNumber) {
        log.info("根据订单号查询支付记录: orderNumber={}", orderNumber);
        return Result.success(paymentService.getPaymentByOrderNumber(orderNumber));
    }

    /**
     * 获取支付统计信息
     *
     * @return 支付统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getPaymentStatistics() {
        log.info("获取支付统计信息");
        return Result.success(paymentService.getPaymentStatistics());
    }

    /**
     * 获取支付方式列表
     *
     * @return 支付方式列表
     */
    @GetMapping("/payment-methods")
    public Result<Map<Integer, String>> getPaymentMethods() {
        log.info("获取支付方式列表");
        Map<Integer, String> paymentMethods = new HashMap<>();
        paymentMethods.put(0, "支付宝");
        paymentMethods.put(1, "微信");
        paymentMethods.put(2, "银行卡");
        paymentMethods.put(3, "余额");
        return Result.success(paymentMethods);
    }
} 